<!--  -->
<template>
  <!-- 就诊人组件的静态结构 -->
  <el-card class="box-card">
    <template #header>
      <div class="card-header">
        <span>就诊人管理</span>
        <el-button class="button" type="primary" :icon="User" @click="addUser"
          >添加就诊人</el-button
        >
      </div>
    </template>
    <!-- 就诊人管理模块展示就诊人信息的结构 -->
    <div class="visitor" v-if="scene == 0">
      <Visitor
        @changeScene="changeScene"
        @removeUser="removeUser"
        class="item"
        v-for="(user, index) in userArr"
        :key="user.id"
        :user="user"
        :index="index"
      />
    </div>
    <!-- 添加就诊人|修改已有的就诊人信息的结构 -->
    <div class="form" v-if="scene == 1">
      <el-divider content-position="left">就诊人信息</el-divider>
      <el-form style="width: 60%; margin: 10px auto" ref="form1"   :model="userParams"   :rules="rules1" >
        <el-form-item label="用户姓名"  prop="name">
          <el-input
            placeholder="请你输入用户姓名"
            v-model="userParams.name"
          >
          </el-input>
        </el-form-item>
        <el-form-item label="证件类型" prop="certificatesType">
          <el-select
            placeholder="请你选择证件的类型"
            style="width: 100%"
            v-model="userParams.certificatesType"
          >
            <el-option
              v-for="item in certationArr"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码" prop="certificatesNo">
          <el-input
            placeholder="请你输入证件号码"
            v-model="userParams.certificatesNo"
          ></el-input>
        </el-form-item>
        <el-form-item label="用户性别" prop="sex" >
          <el-radio-group v-model="userParams.sex"  :disabled="userParams.certificatesNo==''?true:false" >
            <el-radio :label="1">男</el-radio>
            <el-radio :label="0">女</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="出生日期" prop="birthdate">      
          <el-date-picker
            type="date"
            placeholder="请你选择日期"
            value-format="YYYY-MM-DD"
            v-model="userParams.birthdate"
           :disabled="userParams.certificatesNo==''?true:false"
          />
        </el-form-item>
        <el-form-item label="手机号码" prop="phone">
          <el-input
            placeholder="请你输入手机号码"
            v-model="userParams.phone"
          ></el-input>
        </el-form-item>
      </el-form>

      <el-divider content-position="left"
        >建档信息（完善后部分医院首次就诊不排队建档）</el-divider
      >
      <el-form style="width: 60%; margin: 10px auto" ref="form2"  :model="userParams"   :rules="rules2" >
        <el-form-item label="婚姻状况" prop="isMarry">
          <el-radio-group v-model="userParams.isMarry">
            <el-radio :label="0">未婚</el-radio>
            <el-radio :label="1">已婚</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="自费/医保" prop="isInsure">
          <el-radio-group v-model="userParams.isInsure">
            <el-radio :label="0">自费</el-radio>
            <el-radio :label="1">医保</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="当前的住址" prop="addressSelected">
          <el-cascader :props="props" v-model="userParams.addressSelected" />
        </el-form-item>
        <el-form-item label="详细地址" prop="address">
          <el-input
            placeholder="请你输入用户详细地址"
            v-model="userParams.address"
          ></el-input>
        </el-form-item>
      </el-form>

      <el-divider content-position="left">联系人信息（选填）</el-divider>
      <el-form style="width: 60%; margin: 10px auto" label-width="80" ref="form3" hide-required-asterisk=true  :model="userParams"   :rules="rules3" >
        <el-form-item label="用户姓名" prop="contactsName" >
          <el-input
            placeholder="请你输入用户姓名"
            v-model="userParams.contactsName"
          ></el-input>
        </el-form-item>
        <el-form-item label="证件类型" prop="contactsCertificatesType">
          <el-select
            placeholder="请你选择证件的类型"
            style="width: 100%"
            v-model="userParams.contactsCertificatesType"
          >
            <el-option
              v-for="item in certationArr"
              :key="item.id"
              :label="item.name"
              :value="item.value"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="证件号码"     prop="contactsCertificatesNo">
          <el-input
            placeholder="请你输入证件号码"
            v-model="userParams.contactsCertificatesNo"
          ></el-input>
        </el-form-item>
        <el-form-item label="手机号码" prop="contactsPhone">
          <el-input
            placeholder="请你输入手机号码"
            v-model="userParams.contactsPhone"
          ></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="default" @click="submit"
            >提交</el-button
          >
          <el-button type="primary" size="default" @click="reset"
            >重写</el-button
          >
        </el-form-item>
      </el-form>
    </div>
  </el-card>
</template>

<script setup lang='ts'>
// @ts-ignore 
// 引入element-plus图标
 import {
 User,
} from '@element-plus/icons-vue';
import {reqGetUser} from '@/api/hospital/index';
import {onMounted,ref,reactive,watch,computed} from 'vue';
import type {UserResponseData,UserArr} from '@/api/hospital/type';
import {reqCertationType,reqCity,reqAddOrUpdateUser} from '@/api/user/index';
import type {CertationTypeResponseData,CertationType,AddOrUpdateUser} from '@/api/user/type';
import type {CascaderProps} from 'element-plus'
// ts-ignore 
import {ElMessage} from "element-plus";
// 引入路由器与路由方法
import {useRoute,useRouter} from 'vue-router';


// 存储全部就诊人信息
let userArr=ref<UserArr>([]);
// 定义一个响应式数据：决定卡片的身体部分的展示内容
let scene=ref<number>(0);
// 存储证件类型的数据
let certationArr=ref<CertationType>([]);
// 收集新增就诊人的数据
let userParams=reactive<AddOrUpdateUser>({
  name:'',
  certificatesType:'',
  certificatesNo:'',
  sex:0,
  birthdate:'',
  phone:'',
  isMarry:0,
  isInsure:0,
  addressSelected:[],
  address:'',
  contactsName:'',
  contactsCertificatesType:'',
  contactsCertificatesNo:'',
  contactsPhone:'',
  provinceCode: '',
  cityCode: '',
  districtCode:'',
})
let $route=useRoute();
let $router=useRouter();
// 获取form1,form2,form3组件
let form1=ref();
let form2=ref();
let form3=ref();


   
// 组件挂载完毕获取一次就诊人的信息
onMounted(()=>{    
  // 获取就诊人信息
  getAllUser();
  // 获取证件类型的数据
  getCertationType();
  // 判断：当前这个路由组件是不是从挂号组件而来【挂号组件而来，路径上是携带query参数type=add】
  if($route.query.type=='add'){
    scene.value=1;
  }
  if($route.query.type=='edit'){
    scene.value=1;
  }
  
})

// 获取全部就诊人信息
const getAllUser=async()=>{
  let result:UserResponseData=await reqGetUser();
  // console.log(result);
  
  if(result.code==200){
    userArr.value=result.data;
  }
}
// 添加就诊人按钮的回调
const addUser=()=>{ 
  // 清空上一次用户数据
  reset();
  // 切换场景为1
  scene.value=1;
}
// 就诊人子组件自定义事件的回调
const changeScene=(user:AddOrUpdateUser)=>{
  scene.value=1;
  // console.log(user);
  // 收集已有的就诊人信息
  // console.log(userParams.addressSelected[0]+"-"+userParams.addressSelected[1]+"-"+userParams.addressSelected[2]);
  userParams.addressSelected[0]=user.provinceCode;
  userParams.addressSelected[1]=user.cityCode;
  userParams.addressSelected[2]=user.districtCode;
  Object.assign(userParams,user);
  
}
const reset=()=>{
  Object.assign(userParams,{
      id:null,
      name:'',
      certificatesType:'',
      certificatesNo:'',
      sex:0,
      birthdate:'',
      phone:'',
      isMarry:0,
      isInsure:0,
      addressSelected:[],
      address:'',
      contactsName:'',
      contactsCertificatesType:'',
      contactsCertificatesNo:'',
      contactsPhone:'',
      provinceCode: '',
      cityCode: '',
      districtCode:'',
      })
}
// 获取证件类型的接口
const getCertationType=async()=>{
  let result:CertationTypeResponseData=await reqCertationType();
  if(result.code==200){
    certationArr.value=result.data;
  }
}
// 级联选择器数据
const props:CascaderProps ={
  lazy:true,//懒加载数据
  // 加载级联选择器数据方法
  async lazyLoad(node:any,resolve:any){
    let result:any=await reqCity(node.data.id||'86'); 
    // 整理数据
    let showData=result.data.map(((item:any)=>{     
      return{
        id:item.id,
        label:item.name,
        value:item.value,
        leaf:!item.hasChildren
      }
    }));      
    // 注入组件需要展示的数据
    resolve(showData)    
  }
}





// 自定义校验规则姓名方法
const validatorName=(rule:any,value:any,callBack:any)=>{
  // rule:即为当前校验字段的校验规则对象
  const reg=/^[\u00B7\u3007\u3400-\u4DBF\u4E00-\u9FFF\uE000-\uF8FF\uD840-\uD8C0\uDC00-\uDFFF\uF900-\uFAFF]+$/;
  if(reg.test(value)){
    callBack();
  }else{
    callBack(new Error("请输入正确中国人的名字"));
  }
}
// 证件类型校验的方法
const validatorType=(ryle:any,value:any,callBack:any)=>{
  if(value=='10'||value=='20'){
    callBack();
  }else{
    callBack(new Error('请选择证件的类型'));
  }
}
// 证件号码的校验方法
const validatorNo=(rule:any,value:any,callBack:any)=>{
  let sfz=/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
  if(sfz.test(value)){ 
     userParams.certificatesNo=value;     
      callBack();
  }else{
    callBack(new Error('请输入正确的身份证或者户口本的号码'));
  }
}
// 性别的校验方法
const validatorSex=(rule:any,value:any,callBack:any)=>{   
  let sex= userParams.certificatesNo.substring(16,17);    
  console.log((sex%2)==value);
  console.log(value);
  
  
  if(sex%2==value){
    callBack();
  }else{
    callBack(new Error('请选择您真实的性别'));
  }
}

// 出生日期的校验方法
const validatorBirthdate=(rule:any,value:any,callBack:any)=>{
 
  
     let y=userParams.certificatesNo.substring(6,10)+'-'+userParams.certificatesNo.substring(10,12)+'-'+userParams.certificatesNo.substring(12,14);
      // console.log(y);
       if(value==y){
          callBack();
        }else {
          callBack(new Error('请选择出生日期'));
        }
}
// 手机号码的校验方法
const validatorPhone=(rule:any,value:any,callBack:any)=>{
  
  // rule:即为当前校验字段的校验规则对象
  let reg=/^1\d{10}$/;
  if(reg.test(value)){
    callBack();
  }else{
    callBack(new Error("请输入正确的电话号码"));
  }
}
// /^[1-9]\d{5}[1-9]\d{3}((0\d)|(1[0-2]))(([0|1|2]\d)|3[0-1])\d{4}$/
// /\d{9}
// 表单校验规则对象
const rules1={
  // 用户姓名的校验规则
  // required:true,代表当前字段无比进行校验
  name:[
    {
      required:true,
      validator:validatorName,
    },
  ], 
  certificatesType:[
    {
      required:true,
      validator:validatorType,
    },
  ],
   certificatesNo:[
    {
      required:true,
      validator:validatorNo,
    },
  ],
    sex: [
      {
        required: true,
        validator:validatorSex,
      },
    ],
  birthdate: [
    {
      required: true,
      validator:validatorBirthdate,
    },
  ],
   phone: [
    {
      required: true,
      validator:validatorPhone,
    },
  ],
};

// 自定义校验规则当前方法
const validatorAddressSelected=(rule:any,value:any,callBack:any)=>{
  // rule:即为当前校验字段的校验规则对象 
  if(value.length!=0){
    callBack();
  }else{
    callBack(new Error("请选择当前住址"));
  }
}
// 自定义校验规则姓名方法
const validatorAddress=(rule:any,value:any,callBack:any)=>{
  // rule:即为当前校验字段的校验规则对象 
  if(value){
    callBack();
  }else{
    callBack(new Error("请输入详细地址"));
  }
}
const rules2={
  // 用户姓名的校验规则
  // required:true,代表当前字段无比进行校验
  addressSelected:[
    {
      required:true,
      validator:validatorAddressSelected,
    },
  ], 
  address:[
    {
      required:true,
      validator:validatorAddress,
    },
  ]
};

// 自定义校验规则姓名方法
const validatorContactsName=(rule:any,value:any,callBack:any)=>{
  // rule:即为当前校验字段的校验规则对象
      if(value){
          const reg=/^[\u00B7\u3007\u3400-\u4DBF\u4E00-\u9FFF\uE000-\uF8FF\uD840-\uD8C0\uDC00-\uDFFF\uF900-\uFAFF]+$/;
          if(reg.test(value)){
            callBack();
          }else{
            callBack(new Error("请输入正确中国人的名字"));
        }
     }else {
				callBack();
			}
}
// 证件类型校验的方法
const validatorContactsCertificatesType=(ryle:any,value:any,callBack:any)=>{
 if(value){
    if(value=='10'||value=='20'){
     callBack();
    }else{
      callBack(new Error('请选择证件的类型'));
    }
 }else{
  callBack();
 }
}
// 证件号码的校验方法
const  validatorContactsCertificatesNo=(rule:any,value:any,callBack:any)=>{
  if(value){
      let sfz=/^[1-9]\d{5}(18|19|20)\d{2}((0[1-9])|(1[0-2]))(([0-2][1-9])|10|20|30|31)\d{3}[0-9Xx]$/;
    if(sfz.test(value)){
      callBack();
    }else{
      callBack(new Error('请输入正确的身份证或者户口本的号码'));
    }
  }else{
    callBack();
  }
}
// 手机号码的校验方法
const validatorContactsPhone=(rule:any,value:any,callBack:any)=>{
  
  // rule:即为当前校验字段的校验规则对象
  let reg=/^1\d{10}$/;
  if(reg.test(value)){
    callBack();
  }else{
    callBack(new Error("请输入正确的电话号码"));
  }
}
const rules3={
  // 用户姓名的校验规则
  // required:true,代表当前字段无比进行校验
  contactsName:[
    {
      required:true,
      validator:validatorContactsName,
    },
  ], 
  contactsCertificatesType:[
    {
      required:true,
      validator:validatorContactsCertificatesType,
    },
  ],
     contactsCertificatesNo:[
    {
      required:true,
      validator:validatorContactsCertificatesNo,
    },
  ],
   contactsPhone:[
    {
      required:true,
      validator:validatorContactsPhone,
    },
  ],
};
// 提交按钮的方法的回调
const submit=async()=>{  
      userParams.provinceCode=userParams.addressSelected[0],
      userParams.cityCode=userParams.addressSelected[1],
      userParams.districtCode=userParams.addressSelected[2]
   // 全部的表单校验通过返回一个成功的promise
  // 如果有一个表单校验失败返回的是一个失败的promise对象，后面的语句就不再执行了
    await form1.value.validate();
    await form2.value.validate();
    await form3.value.validate();
  // 要么新增就诊人|更新一个已有的就诊人
  try {
    // 要么新增用户成功|更新已有的用户成功
    await reqAddOrUpdateUser(userParams);
    // 提示文字
    ElMessage({
      type:"success",
      message:userParams.id?"更新成功":"新增成功",
    });
    // console.log(userParams.sex+'---'+userParams.isMarry);
    
    // 判断提交按钮的时候是否从预约按钮而来
    if($route.query.type){
      $router.back();
    }else{
      // 切换场景为零
       scene.value=0;
    }
    // 在获取全部的就诊人的信息
    getAllUser();
  } catch (error) {
    ElMessage({
      type:"success",
      message:userParams.id?"更新失败":"新增失败",
    });
  }
};


// 监听全部就诊人的数据
watch(
  ()=>userArr.value,
  ()=>{
    if($route.query.type=='edit'){
      let user=userArr.value.find((item:any)=>{
        return item.id==$route.query.id;
      });
      userParams.addressSelected[0]=user.provinceCode;
      userParams.addressSelected[1]=user.cityCode;
      userParams.addressSelected[2]=user.districtCode;
      Object.assign(userParams,user)
    }
  },
)

// 子组件自定义事件：删除按钮触发
const removeUser=()=>{
  // 再次获取全部的就诊人的信息
  getAllUser();
}
</script>
<style scoped lang='scss'>
.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}
.visitors {
  display: flex;
  flex-wrap: wrap;
  .item {
    width: 32%;
    margin: 5px;
  }
}
</style>